import { defineStore } from "pinia";
import { ref } from "vue";
import { deepMerge, storage } from "../utils";
import { router } from "../router";
import { service } from "../service";
import io from "@hyoga/uni-socket.io";
import { isDev, config } from "../config";

// 本地缓存
const data = storage.info();

const useUserStore = defineStore("user", function () {
	// 标识
	const token = ref(data.token || "");
	let socket = ref()
	let socketId = ref()
	// 设置标识
	function setToken(data : {
		token : string;
		expire : number;
		refreshToken : string;
		refreshExpire : number;
	}) {
		token.value = data.token;
		// 访问
		storage.set("token", data.token, data.expire - 5);
		// 刷新
		storage.set("refreshToken", data.refreshToken, data.refreshExpire - 5);
		socketLink()
	}
	// 断开连接
	function diSocketLink() {
		socketId.value = ""
		if(socket.value){
			socket.value.disconnect()
		}
		
	}
	// 链接socket
	function socketLink() {
		if (socket.value) {
			diSocketLink()
		}
		socket.value = io(`${config.socketBaseUrl}?token=${token._value}`, {
			transports: ["websocket", "polling"]
		});
		socket.value.on("connect", () => {
			const { id } = socket.value;
			socketId.value = id
			console.log("socket连接成功", socketId.value)
			socket.value.on(id, (message : any) => {
				let { code, msg } = message
				if (code == 1015) {
					uni.showToast({
						title: msg ? msg : '缺少必要参数',
						icon: "none"
					})
					setTimeout(() => {
						router.push({
							path: '/pages/user/edit'
						});
					}, 1000)
				} else if (code == 1016) {
					uni.showToast({
						title: "登录失效",
						icon: "none"
					})
					setTimeout(() => {
						logout()
					}, 1000)
				} else if (code != 1000) {
					uni.showToast({
						title: msg ? msg : '错误',
						icon: "none"
					})
				}
			})
		})
		socket.value.on("disconnect", () => {
			console.log("socket断开连接")
		})
		socket.value.on("error", (err : any) => {
			console.log(err)
		})
	}
	
	// 刷新标识
	async function refreshToken() {
		return service.user.login
			.refreshToken({
				refreshToken: storage.get("refreshToken"),
			})
			.then((res) => {
				setToken(res);
				return res.token;
			});
	}

	// 用户信息
	const info = ref<Eps.UserInfoEntity | undefined>(data.userInfo);

	// 设置用户信息
	function set(value : Eps.UserInfoEntity) {
		info.value = value;
		storage.set("userInfo", value);
		socketLink()
	}

	// 更新用户信息
	async function update(data : Eps.UserInfoEntity & { [key : string] : any }) {
		set(deepMerge(info.value, data));
		socketLink()
		return service.user.info.updatePerson(info.value);

	}

	// 清除用户
	function clear() {
		storage.remove("userInfo");
		storage.remove("token");
		storage.remove("refreshToken");
		token.value = "";
		info.value = undefined;
	}

	// 退出
	function logout() {
		clear();
		diSocketLink()
		router.login({ reLaunch: true });
	}

	// 获取用户信息
	async function get() {
		return service.user.info
			.person()
			.then((res) => {
				if (res) {
					set(res);
				}
				return res;
			})
			.catch(() => {
				logout();
			});
	}

	return {
		token,
		setToken,
		refreshToken,
		info,
		get,
		set,
		update,
		logout,
		socketLink,
		socket,
		diSocketLink,
		socketId
	};
});

export { useUserStore };